package org.demo.redis;
import	java.util.concurrent.CountDownLatch;

import lombok.extern.slf4j.Slf4j;
import org.demo.redis.service.Receiver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@SpringBootApplication
@Slf4j
public class RedisMQApplication {

	public static void main(String[] args) throws InterruptedException {
		ConfigurableApplicationContext ctx = SpringApplication.run(RedisMQApplication.class, args);

		StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
		CountDownLatch latch = ctx.getBean(CountDownLatch.class);
		log.info("Sending message ... ");
		template.convertAndSend("chat", "Hello from redis!");
		latch.await();
		System.exit(0);
	}

	@Bean
	public Receiver receiver(CountDownLatch latch) {
	    return new Receiver(latch);
	}

	@Bean
	public CountDownLatch latch(){
		return new CountDownLatch(1);
	}

	@Bean
	public StringRedisTemplate template(RedisConnectionFactory connection){
		return new StringRedisTemplate(connection);
	}

	@Bean
	public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
												   MessageListenerAdapter listenerAdapter){
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
		return container;
	}

	@Bean
	public MessageListenerAdapter listenerAdapter(Receiver receiver){
		return new MessageListenerAdapter(receiver, "receiveMessage");
	}
}
